package com.niit.utils;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.niit.entity.Company;
import com.niit.entity.Region;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

public class CompanyQueryApi {
	public static Company apiCompany(String companyName){
		String host = "https://cardnotwo.market.alicloudapi.com";
		String path = "/companyQuery";
		String method = "POST";
		String appcode = "c7366249e5594fcd82204eb3c05b8128";
		Map<String, String> headers = new HashMap<>();
		//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		headers.put("Authorization", "APPCODE " + appcode);
		//根据API的要求，定义相对应的Content-Type
		headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		Map<String, String> querys = new HashMap<>();
		Map<String, String> bodys = new HashMap<>();
		bodys.put("com", companyName);
		bodys.put("X_Ca_Error_Code", "OFF");

		try {
			HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
			String string = EntityUtils.toString(response.getEntity());
			System.out.println(string);
			JsonObject jsonObject = JsonParser.parseString(string).getAsJsonObject();
			JsonObject result = jsonObject.getAsJsonObject("result");

			Company company = new Company();
			company.setCompanyName(result.get("companyName").getAsString());
			company.setCreditNo(result.get("creditCode").getAsString());
			company.setCompanyType(result.get("regTypeCategory").getAsString());
			company.setCompanyStatus(result.get("businessStatusCategory").getAsString());
			company.setCompanyAddress(result.get("address").getAsString());
			LocalDate regDate = LocalDate.parse(result.get("regDate").getAsString());
			company.setEstablishTime(regDate.atStartOfDay());
			company.setLegalPerson(result.get("faRen").getAsString());
			company.setAddressRegion(new Region(){{setCode(result.get("adCode").getAsLong());}});
			return company;
		} catch (Exception ignored) {}
		return null;
	}
}
